package com.chatai.service;

import com.chatai.model.ChatMessage;
import com.chatai.model.ChatRoom;
import com.chatai.model.User;
import com.chatai.repository.ChatMessageRepository;
import com.chatai.repository.ChatRoomRepository;
import com.chatai.repository.UserRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@Service
public class ChatService {
    @Autowired
    private ChatMessageRepository chatMessageRepository;

    @Autowired
    private ChatRoomRepository chatRoomRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private AuthService authService;

    @Autowired
    private AIService aiService;

    // 创建新的私聊或群聊
    public ChatRoom createChatRoom(String name, String roomType, Set<Long> memberIds) {
        User currentUser = authService.getCurrentUser();
        
        ChatRoom chatRoom = new ChatRoom();
        chatRoom.setName(name);
        chatRoom.setRoomType(roomType);
        chatRoom.setCreator(currentUser);
        
        // 添加创建者为成员
        chatRoom.addMember(currentUser);
        
        // 添加其他成员
        if (memberIds != null) {
            for (Long memberId : memberIds) {
                if (!memberId.equals(currentUser.getId())) {
                    // 这里简化处理，实际应该从数据库查询用户
                    User member = new User();
                    member.setId(memberId);
                    chatRoom.addMember(member);
                }
            }
        }
        
        return chatRoomRepository.save(chatRoom);
    }
    
    // 发送消息
    public ChatMessage sendMessage(Long chatRoomId, String content) {
        User currentUser = authService.getCurrentUser();
        
        // 检查聊天室是否存在
        ChatRoom chatRoom = chatRoomRepository.findById(chatRoomId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "聊天室不存在"));
        
        // 检查用户是否是聊天室成员
        if (!chatRoom.getMembers().contains(currentUser)) {
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "您不是该聊天室成员");
        }
        
        // 创建并保存消息
        ChatMessage message = new ChatMessage();
        message.setContent(content);
        message.setSender(currentUser);
        message.setChatRoom(chatRoom);
        message.setSenderType("user");
        message.setTimestamp(LocalDateTime.now());
        message.setAIResponse(false);
        
        return chatMessageRepository.save(message);
    }

    // 获取聊天室消息历史
    public List<ChatMessage> getChatRoomMessages(Long chatRoomId) {
        User currentUser = authService.getCurrentUser();
        
        // 检查聊天室是否存在
        ChatRoom chatRoom = chatRoomRepository.findById(chatRoomId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "聊天室不存在"));
        
        // 管理员可以查看所有聊天室的消息，普通用户只能查看自己所在聊天室的消息
        if (!currentUser.isAdmin() && !chatRoom.getMembers().contains(currentUser)) {
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "您没有权限查看该聊天室的消息");
        }
        
        return chatMessageRepository.findByChatRoomOrderByTimestampDesc(chatRoom);
    }
    
    // 获取用户的所有聊天室
    public List<ChatRoom> getUserChatRooms() {
        User currentUser = authService.getCurrentUser();
        
        // 管理员可以查看所有聊天室
        if (currentUser.isAdmin()) {
            return chatRoomRepository.findAll();
        }
        
        // 普通用户只能查看自己所在的聊天室
        return chatRoomRepository.findByMembersContaining(currentUser);
    }
    
    // 删除聊天室
    public void deleteChatRoom(Long chatRoomId) {
        User currentUser = authService.getCurrentUser();
        
        // 检查聊天室是否存在
        ChatRoom chatRoom = chatRoomRepository.findById(chatRoomId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "聊天室不存在"));
        
        // 只有管理员或聊天室创建者可以删除聊天室
        if (!currentUser.isAdmin() && !chatRoom.getCreator().getId().equals(currentUser.getId())) {
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "您没有权限删除该聊天室");
        }
        
        // 先删除聊天室的所有消息
        List<ChatMessage> messages = chatMessageRepository.findByChatRoomOrderByTimestampDesc(chatRoom);
        chatMessageRepository.deleteAll(messages);
        
        // 然后删除聊天室
        chatRoomRepository.delete(chatRoom);
    }

    // 获取AI回复
    public ChatMessage getAIResponse(Long chatRoomId, String query) {
        User currentUser = null;
        try {
            currentUser = authService.getCurrentUser();
        } catch (Exception e) {
            // 当无法获取当前用户时，使用默认测试用户
            currentUser = createOrGetDefaultUser();
        }
        
        // 检查聊天室是否存在
        ChatRoom chatRoom = chatRoomRepository.findById(chatRoomId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "聊天室不存在"));
        
        // 调用AI服务获取回复
        String aiResponse = aiService.getAIResponse(query);
        
        // 保存用户消息
        ChatMessage userMessage = new ChatMessage();
        userMessage.setContent(query);
        userMessage.setSender(currentUser);
        userMessage.setChatRoom(chatRoom);
        userMessage.setSenderType("user");
        userMessage.setTimestamp(LocalDateTime.now());
        userMessage.setAIResponse(false);
        chatMessageRepository.save(userMessage);
        
        // 保存AI回复
        ChatMessage aiMessage = new ChatMessage();
        aiMessage.setContent(aiResponse);
        aiMessage.setChatRoom(chatRoom);
        aiMessage.setSenderType("ai");
        aiMessage.setTimestamp(LocalDateTime.now());
        aiMessage.setAIResponse(true);
        chatMessageRepository.save(aiMessage);
        
        return aiMessage;
    }
    
    // 获取或创建与AI的聊天室
    public ChatRoom getOrCreateAIChatRoom() {
        User currentUser = null;
        try {
            currentUser = authService.getCurrentUser();
        } catch (Exception e) {
            // 当无法获取当前用户时，创建或使用默认测试用户
            currentUser = createOrGetDefaultUser();
        }
        
        // 查找用户的AI聊天室，如果不存在则创建
        List<ChatRoom> aiRooms = chatRoomRepository.findByMembersContainingAndRoomType(currentUser, "ai");
        if (!aiRooms.isEmpty()) {
            return aiRooms.get(0);
        }
        
        // 创建AI聊天室
        ChatRoom aiRoom = new ChatRoom();
        aiRoom.setName("AI助手");
        aiRoom.setRoomType("ai");
        aiRoom.setCreator(currentUser);
        aiRoom.addMember(currentUser);
        
        return chatRoomRepository.save(aiRoom);
    }
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    // 创建或获取默认测试用户
    private User createOrGetDefaultUser() {
        // 尝试查找默认用户
        Optional<User> optionalUser = userRepository.findByUsername("test_user");
        if (optionalUser.isPresent()) {
            return optionalUser.get();
        }
        
        // 创建默认用户，使用密码加密
        User defaultUser = new User();
        defaultUser.setUsername("test_user");
        defaultUser.setEmail("test@example.com");
        defaultUser.setPassword(passwordEncoder.encode("password")); // 使用加密密码
        defaultUser.setCreatedAt(LocalDateTime.now());
        defaultUser.setRole("USER");
        return userRepository.save(defaultUser);
    }
}